const listTmpl = require("./tmpl/build/template");
const _ = require("lodash");

/**
 * config {
 *      eventHandler: {
 *          click: function(){
 *          },
 *          delete: function(){
 *          
 *          }
 *      },
 *      container: "",
 *      data: [{
 *          title: "",
 *          body: "",
 *          id: ""      // used for panel body id
 *      }],
 *      collapseId: ""  // used for panel container id
 * }
 */
class CollapseList {
    constructor(config){
        this.container = config.container;
        this.eventHandler = config.eventHandler;
        this.collapseId = config.collapseId;
        this.data = {
            list: ((data)=>{
                _.forEach(data, this.preprocessData);
                return data;
            })(config.data),
            collapseId: this.collapseId
        };
        this.render();
        this.bindEvent();
    }

    preprocessData (data) {
        data.pid = "head-" + data.id;
        data.delete = data.delete === undefined ? true : data.delete;
    }

    render (){
        var html = listTmpl("list", this.data);
        $(this.container).html(html);
    }

    /**
     * 添加 collapse-item
     * {
     *      title: "",
     *      id: "",
     *      body: ""
     * }
     */
    unshift (data) {
        this.preprocessData(data);
        this.data.list.unshift(data);
        var html = listTmpl("item", {list:[data], collapseId: this.collapseId});
        $("#" + this.collapseId).prepend(html);
    }

    hide (itemId) {
        var target = $("#" + itemId);
        if(target){
            $(target).collapse("hide");
        }
    }

    /**
     * 删除 collapse-item
     */
    delete (itemId) {
        var target = $("#" + itemId);
        if(target){
            $(target).parents(".panel").remove();
        }
    }

    bindEvent () {
        var that = this;
        $(this.container).on("click", function(){
            var args = Array.prototype.slice.apply(arguments);
            var event = args[0];
            var target = event.target;
            args.unshift(that);
            if($(target).data("action") === "delete"){
                event.target = $(target).closest(".panel").find(".panel-body")[0];
                that.eventHandler["delete"].apply(this, args);
            }else{
                that.eventHandler["click"].apply(this, args);
            }
        });
    }
}

export default CollapseList;